package setup

import (
	"fmt"
	"os"
	"tone-agent/core"
	"tone-agent/entity"

	"github.com/spf13/viper"
)

func HandleHeartbeatTest() {
	if viper.GetString(entity.ModeConfigKey) == entity.PassiveMode {
		fmt.Printf("该功能只对[active]模式生效(当前配置为[%s]模式)\n", viper.GetString(entity.ModeConfigKey))
		return
	}
	if err := core.SyncHeartbeat(); err != nil {
		fmt.Println("failed：", err.Error())
	} else {
		fmt.Println("success!")
		fmt.Println("tsn:", viper.Get(entity.TSNConfigKey))
		fmt.Println("proxy:", viper.Get(entity.ProxyConfigKey))
		fmt.Println("datetime:", core.GetCurTimeStr())
	}
}

func HandleShowConfig() {
	c := core.ExecCommand("cat", fmt.Sprintf("%s/%s.yaml", entity.ConfigPath, entity.APPName))
	fmt.Println(c)
}

func HandleShowLog() {
	fmt.Println("# " + entity.LogPath + "/" + entity.APPName + ".log")
	if err := core.ExecByStdoutPipe("tail", "-f", entity.LogPath+"/"+entity.APPName+".log"); err != nil {
		fmt.Println("Error executing command")
	}
}

func HandleRestart() {
	core.MyLogger.WithFields(core.LogFields{"command": "toneagent -restart"}).Info(
		"A restart command has been received. Service is about to restart")
	fmt.Println("restart toneagent...")
	res := core.ExecCommand("systemctl", "restart", "toneagent")
	fmt.Println(res)
}

func HandleUpdate() {
	if core.InputConfirm() {
		fmt.Println("upgrade service...")
		core.WriteFile(entity.UpgradeScriptFile, []byte(entity.UpgradeScript), 0755)
		res := core.ExecCommand("bash", entity.UpgradeScriptFile, "latest")
		fmt.Println(res)
		os.Remove(entity.UpgradeScriptFile)
	}
}

func HandleUpgrade() {
	var assignVersion string
	if Upgrade == "latest" {
		assignVersion = "latest"
	} else if Upgrade == "stable" {
		assignVersion = "stable"
	} else {
		assignVersion = Upgrade
	}
	if core.InputConfirm() {
		fmt.Println("upgrade service...")
		if err := core.WriteFile(entity.UpgradeScriptFile, []byte(entity.UpgradeScript), 0755); err != nil {
			fmt.Println("upgrade failed")
		}
		res := core.ExecCommand("bash", entity.UpgradeScriptFile, assignVersion)
		fmt.Println(res)
		os.Remove(entity.UpgradeScriptFile)
	}
}

func HandleVersionList() {
	core.WriteFile(entity.ListVersionScriptFile, []byte(entity.ListVersionScript), 0755)
	res := core.ExecCommand("bash", entity.ListVersionScriptFile)
	fmt.Println(res)
	os.Remove(entity.ListVersionScriptFile)
}

func HandleSetTSN() {
	if core.InputConfirm() {
		core.UpdateConfig(SetTSN, "", "")
	}
}

func HandleSetMode() {
	if core.InputConfirm() {
		core.UpdateConfig("", SetMode, "")
	}
}

func HandleSetProxy() {
	if core.InputConfirm() {
		core.UpdateConfig("", "", SetProxy)
	}
}
